<template>
	<div class="zh-campus-broadcast">
        <nav-header></nav-header>
		<div class="zh-table">
			<div class="zh-table-open clear">
				<div class="zh-open-left fl">
					<div class="open-width" style="width: 160px">
						<el-select v-model="listParam.classroom_id" filterable placeholder="请选择">
						    <el-option
						      v-for="item in installPositionData"
						      :key="item.id"
						      :label="item.name"
						      :value="item.id">
						    </el-option>
						</el-select>
					</div>
					<div class="open-width">
						<el-input v-model="listParam.keyword" placeholder="请输入设备名称、所属教室搜索"></el-input>
					</div>
					<el-button type="primary" @click="searchFunc">搜索</el-button>
				</div>
				<div class="zh-open-right fr">
					<el-button type="primary" @click="saveBox()">添加校园直播</el-button>
					<el-button type="danger" @click="deleteMuilt_confirm()">批量删除</el-button>
				</div>
			</div>
			<div class="zh-table-contents">
				<el-table
				    :data="listData"
				    border
				     @selection-change="tableSelectionChange"
				    max-height="600"
				    style="width: 100%">
				    <el-table-column
				      type="selection"
				      width="50"
				      align="center"
				      fixed>
				    </el-table-column>
				    <el-table-column
				      prop="sname"
				      label="直播名称"
				      align="center"
				      show-overflow-tooltip
				      >
				    </el-table-column>
				    <el-table-column
				      prop="name"
				      label="设备别名"
				      align="center"
				      show-overflow-tooltip
				      >
				    </el-table-column>
				    <el-table-column
				      prop="type"
				      label="类型"
				      align="center"
				      show-overflow-tooltip
				      >
				      		<template slot-scope="scope">
					      	  <div v-html="getType(scope.row.type)"></div>
					      	</template>
				    </el-table-column>
				    <el-table-column
				      prop="cmname"
				      label="安装位置"
				      align="center"
				      show-overflow-tooltip
				      >
				    </el-table-column>
				    <el-table-column
				      prop="ip"
				      label="IP"
				      align="center"
				      show-overflow-tooltip
				      >
				    </el-table-column>
				    <el-table-column
				      prop="4"
				      label="状态"
				      align="center"
				      show-overflow-tooltip
				      >
				      		<template slot-scope="scope">
					      	  <div v-html="getStatus(scope.row.status)"></div>
					      	</template>
				    </el-table-column>
				    <el-table-column
				      prop="5"
				      label="操作"
				      align="center"
				      width="100"
				      show-overflow-tooltip
				      >
				      	<template slot-scope="scope">
			      	        <el-button @click="saveBox(scope.row.sid)" type="text">编辑</el-button>
			      	        <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button">删除</el-button>
			      	    </template>
				    </el-table-column>
				</el-table>
				<div class="table-pagination" v-if="total_number > 10">
					<el-pagination
					    @size-change="handleSizeChange"
					    @current-change="handleCurrentChange"
					    :current-page="listParam.page_index"
					    :page-sizes="[10, 20, 30, 40, 50, 100]"
					    :page-size="listParam.page_size"
					    layout="total, sizes, prev, pager, next, jumper"
					    :total="total_number">
					</el-pagination>
					<div class="pagination-button">
						<el-button
							@click="getList"
							type="primary" icon="el-icon-refresh"
							circle title="刷新数据" size="mini" >
						</el-button>
					</div>
				</div>
			</div>
		</div>
		<!-- 添加校园直播 -->
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="title" :visible.sync="campusBroadcast" class="campusBroadcast" width="500px">
			<el-form :model="addForm" ref="addForm" :rules="rules" status-icon label-position="left" label-width="100px" v-loading="saveBoxLoading.status" :element-loading-text="saveBoxLoading.txt" >
				<el-form-item label="直播设备" prop="recorderid">
			      	<el-select v-model="addForm.recorderid" filterable @change="fillLiveName" placeholder="请选择设备">
			      		 <el-option
					      v-for="item in initSchoolLiveData.recorder"
					      :key="item.id"
					      :label="item.name"
					      :value="item.id">
					    </el-option>
			      	</el-select>
			    </el-form-item>
			    <el-form-item label="直播名称" prop="livename">
			      	<el-input
			      		v-model="addForm.livename"
			      		placeholder="不填则获取设备名称"
			      		autocomplete="off"
			      		:maxlength="parseInt(10)"
			      		clearable>
			      	</el-input>
			    </el-form-item>
			    <el-form-item label="观看权限" prop="roleid">

					<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">不限</el-checkbox>
					<el-checkbox-group v-model="addForm.roleid" @change="handleCheckedCitiesChange">
			      		<template v-for="item in initSchoolLiveData.role">
			      			<el-checkbox  :label="item.id" :key="item.id" >{{item.name}}</el-checkbox>
			      		</template>
			      	</el-checkbox-group>
			    </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
			    <el-button type="primary" @click="saveSchooleLive">确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
  	export default {
	    data() {
		    return {
		    	listData:[],
		    	listParam:{
		    		classroom_id:0,
		    		keyword: '',
		       		page_index:1,
		       		page_size:10,
		    	},
		    	installPositionData:[],
		        total_number:0,
		        typeArr:{0:'0620',1:'0600B',2:'0650',3:'rtmp',4:'rtsp',5:'奥威亚',6:'网动',7:'中庆',8:'锐取',9:'0683',10:'0660'},
				statusArr:{1:'启用',2:'停用'},
				selected:[],
				initSchoolLiveData:{
					role:[],
					recorder:[]
				},

				saveBoxLoading:{
					status:false,
					txt:"初始化数据..."
				},
                campusBroadcast: false,
		    	addForm: {
		    		id:0,
		    		roleid: [],
		    		livename: '',
		    		recorderid: '',
		    	},
		    	rules:{
		    		recorderid: [
        	            { validator: this.checkRecorder, trigger: 'change', required: true }
        	        ],

        	        livename: [
        	            { validator: this.validateContent, trigger: 'blur', required: true }
        	        ],
        	        roleid: [
        	            { validator: this.checkRole, trigger: 'change', required: true }
        	        ],
		    	},
                checkAll: false,
                isIndeterminate: false,
				title: '',
				rowLen: 0,
		    }
		},
		created(){
			this.getInstallPositon();
			this.getList();
		},
		methods: {
			searchFunc(){
				this.listParam.page_index = 1;
				this.getList();
			},
			fillLiveName( recorder_id ){
				for (var i = this.initSchoolLiveData.recorder.length - 1; i >= 0; i--) {
					if(parseInt(this.initSchoolLiveData.recorder[i].id) === recorder_id){
						this.addForm.livename = this.initSchoolLiveData.recorder[i].name
						break;
					}
				}
			},
			saveBox( id = null ){
				this.title = "添加校园直播"
				this.checkAll = false;
				if (this.$refs['addForm']!==undefined) {
				     this.$refs['addForm'].resetFields();
				}
				this.campusBroadcast = true;
				this.saveBoxLoading = {
					status:true,
					txt:"初始化数据..."
				}

				// 重写成功回调
				let success = ( data => {

					this.saveBoxLoading.status = false;
					this.initSchoolLiveData.role = data.data.role;
					this.initSchoolLiveData.recorder = data.data.list;
					this.addForm.id = id;
					this.addForm.livename = data.data.name;
					this.addForm.recorderid = is_empty(id) ? '' : data.data.list[0].id;
					if( !is_empty(id) && data.data.role.length > 0 ){
						for (var i = data.data.role.length - 1; i >= 0; i--) {
							if( parseInt(data.data.role[i].role) === 1 ){

								this.addForm.roleid.push( parseInt( data.data.role[i].id ));
							}

						}
					}

				});

  				this.$ajax.get('api/live/getschool_live_recorder',{params:{id:id},func:{success:success}})
			},
			saveSchooleLive(){
				let valid_res = true;
	    		this.$refs['addForm'].validate((valid) => {
					if ( !valid ) {
						valid_res = false
					}
				});
				if( !valid_res) return false;
				this.saveBoxLoading = {
					status:true,
					txt:"保存数据..."
				}
 	    		let success = ( data=>{
 	    			this.saveBoxLoading.status = false;
	    			this.campusBroadcast = false;
            		this.$message.success(data.msg);
            		this.getList();
            	})
            	let fail = (data =>{
            		this.saveBoxLoading.status = false;
            		this.$message.error(data.msg);
            	})
 	    		if( parseInt(this.addForm.id) > 0 ){
 	    			this.$ajax.put('api/live/school_live',this.addForm,{func:{success:success}})
 	    		}else{
 	    			this.$ajax.post('api/live/school_live',this.addForm,{func:{success:success}})
 	    		}

			},
			getType(val){
				return this.typeArr[parseInt(val)];
			},
			getStatus(val){
				return this.statusArr[parseInt(val)];
			},
			getList(){
            	let success = (data=>{
            		this.listData = data.data.data;
            		this.total_number = data.data.data_sum;
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	this.$ajax.get('api/live/school_live',{params: this.listParam,func:{success:success}})
            },
			getInstallPositon(){
				// 重写成功回调
				let success = ( data => {
					this.installPositionData = data.data;
					this.installPositionData.unshift({id:0,name:'全部安装位置'});
					this.$forceUpdate();//强制渲染
				});

  				this.$ajax.get('api/live/install_position',{params:{},func:{success:success}})
			},
			 //选中
		    tableSelectionChange(val) {
                this.selected = val;
            },
			deleteMuilt_confirm(){
				if( this.selected.length === 0 ) {
					this.$message.warning("请选择要删除的项");
					return false;
				}
				let yes = ( data => {
					this.rowLen = this.selected.length;
					this.deleteMuilt();
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定要删除选中的项吗？'});

			},
			deleteMuilt(){
				var ids = [];
				for (var i = this.selected.length - 1; i >= 0; i--) {
					ids.push(this.selected[i].sid)
				}
				this.delete(ids);
			},
			delete_confirm(obj){
				let yes = ( data => {
					this.rowLen = 1;
					this.delete(obj.sid,0);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 删除吗？'});

			},
			delete(id){
		    	let success = ( data => {
					this.$message.success(data.msg);
					
					if (this.listData.length - this.rowLen === 0) {
						if (this.listParam.page_index > 1) {
							this.listParam.page_index-- ;
						} else {
							this.listParam.page_index = 1;
						}
					}

					this.getList();
				});
		    	this.$ajax.delete('api/live/school_live',{params:{id:id},func:{success:success}})
		    },
		    resetAddForm(){
				this.addForm = {
		    		id:0,
		    		roleid: [],
		    		livename: '',
		    		recorderid: '',
		    	}
			},
			checkRecorder(rule, value, callback){
                if (!isEmpty(value)) {
                    return callback(new Error('请选择设备'));
                }else{
                    callback()
                }
            },
            checkRole(rule, value, callback){
                if (value.length === 0) {
                    return callback(new Error('至少选择一个观看权限'));
                }else{
                    callback()
                }
            },
            // 验证
			validateContent(rule, value, callback){
				if (value === '') {
                  	return callback(new Error('请输入直播名字'));
                } else if (!validateName(value)){
                	return callback(new Error('不能输入空格符号'));
                } else {
                	callback()
                }
			},
            // 全选
			handleCheckAllChange(val) {
				this.addForm.roleid  = [];
				//this.addForm.roleid = this.checkAll ? this.initSchoolLiveData.role : []
				if( this.checkAll ){
					for (var i = this.initSchoolLiveData.role.length - 1; i >= 0; i--) {
						this.addForm.roleid.push(this.initSchoolLiveData.role[i].id);
					}
				}
                let checkCount = this.addForm.roleid.length
        		this.isIndeterminate = false;
		    },
		    // 单选
		    handleCheckedCitiesChange(value) {
		    	let checkedCount = this.addForm.roleid.length
        		this.isIndeterminate = checkedCount > 0 && checkedCount < this.initSchoolLiveData.role.length
        		this.checkAll = checkedCount === this.initSchoolLiveData.role.length
		    },
		     handleSizeChange(val) {
		     	this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getList();
		    },
		},
  	}
</script>
<style lang="scss">
	.zh-campus-broadcast {
		.el-table__body-wrapper table tbody {
			td:nth-child(8) {
				padding: 0;
			}
		}
	}
	.campusBroadcast {
		.el-checkbox-group {
			display: inline-block;
		}
		.el-checkbox {
			margin-left: 0;
			margin-right: 15px;
		}
	}
</style>
